package indi.kider.server.apabus.api;

import indi.kider.common.constant.EmployeeRoleCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.apabus.*;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.employee.Employee;
import indi.kider.server.apabus.service.ApabusService;
import indi.kider.server.apabus.service.related.AuthcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping(value = "apartbus")
public class ApabusController {

    @Autowired
    private ApabusService apabusService;

    @Autowired
    private AuthcService authcService;
//    /**
//     * @api {POST} /reletHouse
//     * @apiGroup apartbus
//     * @apiDescription 用户续租
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/reletHouse
//     * {"newExpireDate":"2019-05-06","newRental":"2019","rentId":"82"}
//     * @apiSuccessExample {json} 返回样例:
//     * {"status": "202","msg": "保存成功！","data": ""}
//     */
//    @PutMapping("/reletHouse")
//    public CommonResponse<Rent> reletHouse(@RequestBody Relet relet) {
//        try {
//             apabusService.reletHouse(relet);
//            return CommonResponse.buildUpdateSuccessResponse("");
//        } catch (Exception e) {
//            return CommonResponse.buildExceptionResponse(e);
//        }
//    }
//    /**
//     *  锁住入住的简单校验。
//     */
//    private static Map<Long, Rent> key = new ConcurrentHashMap<Long, Rent>();
//    /**
//     * @api {POST} /rentHouse
//     * @apiGroup apartbus
//     * @apiDescription 用户租房
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/rentHouse
//     * {"rentDate":"2018-05-06","expireDate":"2019-05-06","housesId":"82","initWaterReading":"10","initPowerReading":"10","tenantName":"wbb","tenantTel":"13333333333","cardId":"44","remark":"44"}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 1
//     * }
//     */
//    @PostMapping("/rentHouse")
//    public CommonResponse<Rent> rentHouse(@RequestBody RentVo rentvo) {
//        try {
//            Long housesId = rentvo.getHousesId();
//            if (key.containsKey(housesId))
//                throw new Exception("房源被锁定");
//            key.put(housesId, rentvo);
//
//            if(!apabusService.hasRent(housesId))
//                throw new Exception("房源还在租住状态");
//
//
//            Rent result = apabusService.rentHouses(rentvo);
//            return CommonResponse.buildAddSuccessResponse(result);
//        } catch (Exception e) {
//            return CommonResponse.buildExceptionResponse(e);
//        } finally {
//            key.remove(rentvo.getHousesId());
//        }
//    }

//    @PostMapping("/rentHouseForImport")
//    public CommonResponse<Rent> rentHouseForImport(@RequestBody RentVo rentvo) {
//        try {
//            Rent result = apabusService.rentHouseForImport(rentvo);
//            return CommonResponse.buildAddSuccessResponse(result);
//        } catch (Exception e) {
//            return CommonResponse.buildExceptionResponse(e);
//        }
//    }


//    /**
//     * @api {POST} /enterprise
//     * @apiGroup apartbus
//     * @apiDescription 内部使用 企业租房
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/enterprise/
//     * {"employeeId":1,"enterpriseId":2,"housesIds":[1,2]}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 2
//     * }
//     */
//    @PostMapping("/rentOutline")
//    public CommonResponse<RentOutline> enterpriseRent(@RequestBody RentOutline rentOutline) {
//        return CommonResponse.buildAddSuccessResponse(
//                apabusService.insertRentOutLine(rentOutline));
//    }


//    /**
//     * @api {POST} /enterprise
//     * @apiGroup apartbus
//     * @apiDescription 企业租房
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/enterprise/
//     * {"employeeId":1,"enterpriseId":2,"housesIds":[1,2]}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 2
//     * }
//     */
//    @PostMapping("/enterprise")
//    public CommonResponse enterpriseRent(@RequestBody EnterpriseRentModel enterpriseRentModel) {
//        return CommonResponse.buildAddSuccessResponse(
//                apabusService.rentHousesToContract(enterpriseRentModel.getHousesIds(),
//                        enterpriseRentModel.getEnterpriseId(),
//                        enterpriseRentModel.getEmployeeId()));
//    }

//    /**
//     * @api {PUT} /rentHouse
//     * @apiGroup apartbus
//     * @apiDescription 用户退房
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/rentHouse
//     * {"id":1,"housesId":12,"tenantId":13}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "202",
//     * "msg": "保存成功！",
//     * "data": 1
//     * }
//     */
//    @PutMapping("/rentHouse")
//    public CommonResponse checkOutHouse(@RequestBody Rent rent) {
//        try {
//            apabusService.rentHouses(rent.getHousesId(),
//                    rent.getTenantId(),
//                    rent.getId());
//            return CommonResponse.buildUpdateSuccessResponse("");
//        } catch (Exception e) {
//            return CommonResponse.buildExceptionResponse(e);
//        }
//    }

//    /**
//     * @api {PUT} /enterprise
//     * @apiGroup apartbus
//     * @apiDescription 企业用户退房
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/enterprise
//     * {"housesId":null,"remark":null}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 1
//     * }
//     */
//    @PutMapping("/enterprise")
//    public CommonResponse checkOutEnterpriseHouse(@RequestBody EnterpriseRentModel enterpriseRentModel) {
//        return CommonResponse.buildUpdateSuccessResponse(
//                apabusService.rentHousesToContract(enterpriseRentModel.getHousesIds(),
//                        enterpriseRentModel.getEnterpriseId())
//        );
//    }
//    /**
//     * @api {POST} /serviceDelivery
//     * @apiGroup apartbus
//     * @apiDescription 服务提供
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/serviceDelivery
//     * {"busType":1,"busdeis":"电灯坏了","rentId":1,"waiterId":1}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": ""
//     * }
//     */
//    @PostMapping("/serviceDelivery")
//    public CommonResponse serviceDelivery(@RequestBody ServiceDelivery serviceDelivery) {
//        apabusService.rentBusSubmit(serviceDelivery.getBusType(),
//                serviceDelivery.getBusdeis(),
//                serviceDelivery.getRentId(),
//                serviceDelivery.getWaiterId());
//        return CommonResponse.buildAddSuccessResponse("");
//    }

//    /**
//     * @api {POST} /rent/release
//     * @apiGroup tenant
//     * @apiDescription 获取租房信息
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/human-resources/apabus/apartbus/rent/housecount
//     * @apiSuccessExample {json} 返回样例:
//     * {"status":"200","msg":"查询成功！","data":{"rows":[{"id":1,"communityId":1,"houseNumb":"1","building":"1","unit":null,"area":null,"heading":null,"cnt1":null,"cnt2":null,"e2url":null,"e1url":null,"h4url":null,"h3url":null,"h2url":null,"h1url":null,"outCode":null,"waterMeter":null,"powerMeter":null,"priceSet":null,"deposit":null,"state":1,"devs":null,"netCost":null,"propertyCosts":null,"powerCost":null,"waterCost":null,"gasCost":null,"rent":{"id":1,"housesId":1,"communityId":1,"tenantId":1,"rentDate":"2018-05-15 00:00:00","state":1,"remark":"1","priceSet":"123","setLease":123,"leaseType":"12","deposit":"123","depositRemark":"123","initWaterRead":"132","initPowerRead":"123","payCycle":1,"wxopenId":"1","tenantName":"2123","tenantTel":"123","houseNumb":"123","building":"123","unit":"132","address":"123","community":"123"},"decs":"null","stateName":"已租"}],"total":1,"size":0}}
//     */
//    @PostMapping("/rent/release")
//    public CommonResponse release(@RequestBody Houses houses) {
//        apabusService.release(houses.getId(),houses.getReleaseState());
//        return CommonResponse.buildAddSuccessResponse("");
//    }

//    /**
//     * @api {POST} /list
//     * @apiGroup apartbus
//     * @apiDescription 根据字段查询获取服务列表（分页）
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/list
//     * {"num":"0","size":"8","query":{"housesId":1,"busType":1,"insTime":"2018-04-10","state":"工单","tenantName":null,"tenantTel":null}}
//     * @apiSuccessExample {json} 返回样例:
//     * {"status":"200","msg":"查询成功！","data":{"rows":[{"busType":null,"community":null,"des":null,"employeeId":null,"evaluation":null,"evsu":null,"evsuTime":null,"houses":null,"housesId":null,"id":null,"insTime":null,"result":null,"resutlTime":null,"state":null,"tenantId":null,"tenantName":null,"tenantTel":null,"waiter":null,"waiterTime":null}],"total":1,"size":0}}
//     */
//    @PostMapping("/list")
//    public CommonResponse<PageResponse<List<Bus>>> getPageServiceList(@RequestBody PageRequest<Bus> request) {
//        Employee employee = authcService.getCurrentUser().getData();
//        if (employee!=null&&!employee.getRoles().equals(EmployeeRoleCons.ADMIN)) {//超级管理员
//            request.getQuery().setEnterpriseId(employee.getEnterpriseId());
//        }
//        request.getQuery().setDelState(StatusCons.VALID);
//        return CommonResponse.buildGetSuccessResponse(apabusService.queryBusList(request));
//    }

//    /**
//     * @api {PUT} /dispatch
//     * @apiGroup apartbus
//     * @apiDescription 服务派单
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/dispatch
//     * {"busId":null,"waiterId":null,des:"问题描述"}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 1
//     * }
//     */
//    @PutMapping("/dispatch")
//    public CommonResponse dispatch(@RequestBody Dispatch dispatch) {
//        return CommonResponse.buildUpdateSuccessResponse(
//                apabusService.dispatch(dispatch));
//    }


//    /**
//     * @api {PUT} /complete
//     * @apiGroup apartbus
//     * @apiDescription 处理服务完成
//     * @apiParamExample 请求样例：
//     * http://localhost:9002/apabus/apartbus/complete
//     * {"busId":null,"resultTime":"处理完成时间","result":"处理结果"}
//     * @apiSuccessExample {json} 返回样例:
//     * {
//     * "status": "201",
//     * "msg": "保存成功！",
//     * "data": 1
//     * }
//     */
//    @PutMapping("/complete")
//    public CommonResponse complete(@RequestBody CompleteBean completeBean) {
//        return CommonResponse.buildUpdateSuccessResponse(
//                apabusService.complete(completeBean));
//    }

    /**
     * @api {PUT} /service
     * @apiGroup apartbus
     * @apiDescription 删除服务delState 2/取消服务delState 3
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/service
     * {"id":1,"delState":2}
     * @apiSuccessExample {json} 返回样例:
     * {"status":"204","msg":"删除成功！","data":""}
     */
    @PutMapping("service")
    public CommonResponse delBus(@RequestBody Bus bus) {
        apabusService.delBus(bus.getId(),bus.getDelState());
        return CommonResponse.buildDelSuccessResponse("");
    }
    /**
     * @api {GET} /reportlist/{month}/{phone}
     * @apiGroup apartbus
     * @apiDescription 时间查询租房报表。
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/reportlist/{month}/{phone}
     * {"num":"0","size":"8","query":{“housesId”：1,"busType":1,"insTime":"2018-04-10","state":"工单","tenantName":null,"tenantTel":null}}
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":[{"id":1,"enterprise":1,"total":2,"rentTotal":0,"month":"2018-05"}]}
     */
    @GetMapping("/reportlist/{month}/{phone}")
    public CommonResponse<List<RentMonthReport>> getReportlist(@PathVariable("month") String month, @PathVariable("phone") String phone) {
        return CommonResponse.buildGetSuccessResponse(apabusService.getReportByMonth(month, phone));
    }

    /**
     * @api {GET} /reportnow
     * @apiGroup apartbus
     * @apiDescription 时间查询租房报表。
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/reportnow/{phone}
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":{"rows":[{"busType":null,"community":null,"des":null,"employeeId":null,"evaluation":null,"evsu":null,"evsuTime":null,"houses":null,"housesId":null,"id":null,"insTime":null,"result":null,"resutlTime":null,"state":null,"tenantId":null,"tenantName":null,"tenantTel":null,"waiter":null,"waiterTime":null}],"total":1,"size":0}}
     */
    @GetMapping("/reportnow/{phone}")
    public CommonResponse<RentMonthReport> getReportNow(@PathVariable("phone") String phone) {
        return CommonResponse.buildGetSuccessResponse(apabusService.getReportByNow(phone));
    }

    /**
     * 内部使用
     *
     * @return
     */
    @GetMapping("/statisticsRental")
    public CommonResponse statisticsRental() {
        return CommonResponse.buildUpdateSuccessResponse(apabusService.updateReport());
    }



    /**
     * @api {PUT} /workOrderReceipt
     * @apiGroup apartbus
     * @apiDescription 服务派单回执
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/workOrderReceipt
     * {"busId":1,"result":"完美解决"}
     * @apiSuccessExample {json} 返回样例:
     * {
     * "status": "201",
     * "msg": "保存成功！",
     * "data": 1
     * }
     */
    @PutMapping("/workOrderReceipt")
    public CommonResponse workOrderReceipt(@RequestBody Dispatch dispatch) {
        return CommonResponse.buildUpdateSuccessResponse(
                apabusService.dispatch(dispatch.getBusId(), dispatch.getResult()));
    }

    /**
     * @api {PUT} /evaluate
     * @apiGroup apartbus
     * @apiDescription 服务派单评分
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/evaluate
     * {"busId":1,"evaluation":5,"evsu":"非常满意"}
     * @apiSuccessExample {json} 返回样例:
     * {
     * "status": "201",
     * "msg": "保存成功！",
     * "data": 1
     * }
     */
    @PutMapping("/evaluate")
    public CommonResponse evaluate(@RequestBody Evaluate evaluate) {
        return CommonResponse.buildUpdateSuccessResponse(
                apabusService.busEvsu(evaluate.getBusId(), evaluate.getEvaluation(), evaluate.getEvsu()));
    }

    /**
     * @api {GET} /rent/{id}
     * @apiGroup apartbus
     * @apiDescription 获取租房信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/apabus/apartbus/rent/1
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":{"id":1,"housesId":1,"tenantId":1,"rentDate":null,"state":1,"remark":null,"priceSet":null,"setLease":null,"leaseType":null,"deposit":null,"depositRemark":null,"payCycle":null,"wxopenId":null,"tenantName":null,"tenantTel":null,"houseNumb":null,"building":null,"unit":null,"initWaterRead":null,"initPowerRead":null,"address":null,"community":null}}
     */
    @GetMapping("/rent/{id}")
    public CommonResponse getRentById(@PathVariable Long id) {
        return CommonResponse.buildGetSuccessResponse(apabusService.getRentById(id));
    }

    /**
     * @api {GET} /rent/house/{id}
     * @apiGroup tenant
     * @apiDescription 获取租房信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/human-resources/apabus/apartbus/rent/house/1
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":{"rows":[{"id":1,"communityId":1,"houseNumb":"1","building":"1","unit":null,"area":null,"heading":null,"cnt1":null,"cnt2":null,"e2url":null,"e1url":null,"h4url":null,"h3url":null,"h2url":null,"h1url":null,"outCode":null,"waterMeter":null,"powerMeter":null,"priceSet":null,"deposit":null,"state":1,"devs":null,"netCost":null,"propertyCosts":null,"powerCost":null,"waterCost":null,"gasCost":null,"rent":{"id":1,"housesId":1,"communityId":1,"tenantId":1,"rentDate":"2018-05-15 00:00:00","state":1,"remark":"1","priceSet":"123","setLease":123,"leaseType":"12","deposit":"123","depositRemark":"123","initWaterRead":"132","initPowerRead":"123","payCycle":1,"wxopenId":"1","tenantName":"2123","tenantTel":"123","houseNumb":"123","building":"123","unit":"132","address":"123","community":"123"},"decs":"null","stateName":"已租"}],"total":1,"size":0}}
     */
    @GetMapping("/rent/house/{id}")
    public CommonResponse<Rent> getRentByHouseId(@PathVariable Long id) {
        return CommonResponse.buildGetSuccessResponse(apabusService.getRentByHouseId(id));
    }

    /**
     * @api {POST} /rent/housecount/{id}
     * @apiGroup tenant
     * @apiDescription 获取租房信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/human-resources/apabus/apartbus/rent/housecount
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":{"rows":[{"id":1,"communityId":1,"houseNumb":"1","building":"1","unit":null,"area":null,"heading":null,"cnt1":null,"cnt2":null,"e2url":null,"e1url":null,"h4url":null,"h3url":null,"h2url":null,"h1url":null,"outCode":null,"waterMeter":null,"powerMeter":null,"priceSet":null,"deposit":null,"state":1,"devs":null,"netCost":null,"propertyCosts":null,"powerCost":null,"waterCost":null,"gasCost":null,"rent":{"id":1,"housesId":1,"communityId":1,"tenantId":1,"rentDate":"2018-05-15 00:00:00","state":1,"remark":"1","priceSet":"123","setLease":123,"leaseType":"12","deposit":"123","depositRemark":"123","initWaterRead":"132","initPowerRead":"123","payCycle":1,"wxopenId":"1","tenantName":"2123","tenantTel":"123","houseNumb":"123","building":"123","unit":"132","address":"123","community":"123"},"decs":"null","stateName":"已租"}],"total":1,"size":0}}
     */
    @PostMapping("/rent/housecount")
    public CommonResponse queryHouseCount() {
        Long id = authcService.getCurrentUserId().getData();
        return CommonResponse.buildGetSuccessResponse(apabusService.queryHouseCount(id));
    }



}
